#from django.forms import ModelForm ?
from google.appengine.ext.db import djangoforms
from gtug.models import Post, Category, User, Profile
from django import forms
from utility import ListPropertyChoice

"""
ModelForm do Post para montar o formulario na tela e persistir automaticamente na base.
"""
class PostForm(djangoforms.ModelForm):
    def __init__(self, *args, **kargs):
        super(PostForm, self).__init__(*args, **kargs)
        c = [(m.key(), m.title) for m in Category.all()]
        self.fields['categories'] = ListPropertyChoice(widget=forms.SelectMultiple, choices = c)
        self.fields.keyOrder = self.Meta.fields
        #self.fields['title'] = forms.CharField(label='xpto', widget=forms.Textarea())
    class Meta:
        model = Post
        fields = ['title','path','body', 'keywords','description','categories']
        exclude = ['readable_categories', 'user_author']

"""
ModelForm do Usuario para montar o formulario na tela e persistir automaticamente na base.
Notar que ele eh usado dentro da view e que renderiza o form automaticamente na tela.
"""
class UserForm(djangoforms.ModelForm):
    email = forms.EmailField()
    def __init__(self, *args, **kargs):
        super(UserForm, self).__init__(*args, **kargs)
        
        # outra forma de fazer isso ?
        self.fields['profile'].choices = [(p.key(), p.name) for p in Profile.all()]
        
    def clean_email(self): 
        email = self.cleaned_data['email'] 
        u = User.gql('WHERE email = :1', email).get()
        
        if u:
            raise forms.ValidationError('This email already exists.')
        else:
            return email
            
    class Meta:
        model = User